package com.botann.projects.service;


import com.botann.projects.base.BaseService;
import com.botann.projects.base.UserDetailType;
import com.botann.projects.constants.Constant;
import com.botann.projects.model.AdminUser;
import com.botann.projects.model.RequestLog;
import com.botann.projects.model.UserSecret;
import com.botann.projects.utils.MD5Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.botann.projects.base.BaseService;
import com.botann.projects.base.UserDetail;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Charging
 * AdminUserService
 * Created by 刘山国 on 2017/11/21.
 * Copyright (c) 2017 刘山国. All rights reserved
 */
@Service
public class AdminUserService extends BaseService implements AdminUserServiceIntf {



    @Override
    public Class loggerClass() {
        return AdminUserService.class;
    }

    @Override
    public void saveRequestLog(RequestLog requestLog) {
        sessionSave(requestLog);
    }

    @Override
    public UserSecret loadUserSecret(Integer userId, Integer type) {
        return sessionGet(UserSecret.class,conditions("userId=","type="),userId,type);
    }

    static long milli30Day = 30*24*60*60*1000L;
    @Override
    public String saveOrUpdateUserSecret(Integer userId, Integer type, String password) {
        Date date = new Date();
        UserSecret userSecret = loadUserSecret(userId,type);
        if (userSecret == null) {
            userSecret = new UserSecret();
            userSecret.setUserId(userId);
            userSecret.setType(UserDetailType.USER_ADMIN.rawValue());
        }
        userSecret.setPassword(password);
//        long l1 = date.getTime();
//        Date d1 = new Date(l1);
//        long l2 = date.getTime()+milli30Day;
//        Date d2 = new Date(l2);
        userSecret.setExpireTime(new Date(date.getTime()+milli30Day));
        String random = Constant.randomStr(30);
        String key = MD5Utils.md5(random);
        userSecret.setSecretKey(key);
        sessionSaveOrUpdate(userSecret);
        return key;
    }

    //
//    @Override
//    public UserDetail loadUserDetail(Integer userId) {
//        StringBuilder hqlBuilder = AdminUser.expandJoinBuilder().append("where a.id=?0 and a.del=false ");
//        AdminUser user = sessionGet(hqlBuilder.toString(),userId);
//        UserDetail userDetail = new UserDetail(user);
//
//        Role role = sessionGet(Role.class,user.getRoleId());
//        userDetail.setRank(role.getRank());
//        userDetail.setRoleName(role.getName());
//        userDetail.setAuthority(role.getAuthority());
//        return userDetail;
//    }


    @Override
    public AdminUser loadAdminUserByUsername(String username) {
        username = username.trim();
        return sessionGet(AdminUser.class,conditions("username=","del="),username.trim(),false);
    }

    @Override
    public AdminUser loadAdminUserByPhone(String phone) {
        return sessionGet(AdminUser.class,conditions("phone=","del="),phone.trim(),false);
    }

    @Override
    public List<AdminUser> loadAdminUsers(String username, String name, Integer roleId, Date startDate, Date endDate) {
        if (roleId!=null && roleId == 0) roleId = null;
        if (name!=null) name = name.trim();
        if (username!=null) username = username.trim();
        StringBuilder hqlBuilder = AdminUser.expandJoinBuilder()
                .append(" where a.del=false ");
        hqlBuilder.append("and a.username like ?0 ");
        hqlBuilder.append("and a.name like ?1 ");
        hqlBuilder.append("and a.createTime between ?2 and ?3 ");
        hqlBuilder.append("and a.roleId= ?4 ");
        hqlBuilder.append("and a.del=false order by a.createTime desc ");
        List<AdminUser> adminUsers = sessionQuery(hqlBuilder.toString(),like(username),like(name),startDate,endDate,roleId);
        adminUsers.forEach((AdminUser user) -> user.setPassword(""));
        return adminUsers;
    }

    @Override
    public AdminUser saveAdminUser(AdminUser user){
        AdminUser adminUser = loadAdminUserByUsername(user.getUsername());
        if (adminUser!=null) throw sgErrorRuntimeException("该用户名已存在");
        Date date = new Date();
        user.setUsername(user.getUsername().trim());
        user.setPhone(user.getPhone().trim());
        user.setCreateTime(date);
        sessionSave(user);

        return user;
    }

    @Override
    public void deleteAdminUsers(String idsJson) {
        JSONArray jsonArray = JSON.parseArray(idsJson);
        for (int i=0;i<jsonArray.size();i++) {
            sessionDelete(AdminUser.class,jsonArray.getInteger(i));
        }
    }

    @Override
    public void updateAdminUserPassword(Integer userId, String password) {
        AdminUser adminUser = sessionGet(AdminUser.class,userId);
        adminUser.setPassword(password.trim());
        sessionUpdate(adminUser);
    }

    @Override
    public void updateAdminUserPassword(String oldPassword, String password) {
        AdminUser adminUser = sessionGet(AdminUser.class,UserDetail.current().getId());
        if (!adminUser.getPassword().equals(oldPassword)) throw sgErrorRuntimeException("原密码输入有误!");
        adminUser.setPassword(password);
        sessionUpdate(adminUser);
    }

    @Override//更新某个管理员的信息，但是密码是不更新的
    public void updateAdminUser(String adminUserJson) {
        AdminUser adminUser = jsonToModel(adminUserJson,AdminUser.class);
        AdminUser originAdminUser = sessionGet(AdminUser.class,adminUser.getId());
        adminUser.setPassword(originAdminUser.getPassword());
        sessionFlushClear();
        sessionUpdate(adminUser);
    }


}
